/* **************************************************************************/
/*COPYRIGHT CCWIN-IN ALL RIGHTS RESERVED. THIS IS AN UNPUBLISHED WORK.      */
/*V8:ConvertMode=Report                                                     */
/*V8:WebEnabled=Yes                                                         */
/*V8:RunMode=Character,Windows                                              */
/*EXTRACTING DATA FROM MFG/PRO                                              */
/****************************************************************************/
/* PROCEDURE NAME        : xxsinvimportapi.p                                */
/* PROCEDURE TYPE        : Supplier invoice API Process                     */
/* DESCRIPTION           :                                                  */
/*                                                                          */     
/* INCLUDE FILES         :                                                  */
/* CALLED BY             :                                                  */
/* CALLED PROCEDURES     :                                                  */
/****************************************************************************/
/* CREATED BY            : Gaoyan                                24-Jul-24  */
/****************************************************************************/ 
/****************************************************************************/
/****************************************************************************/

{us/mf/mfdtitle.i}
{us/bbi/gplabel.i}
{us/wb/wbrp01.i}
{xxjson.i}
{xxcimload.i}


{xxapilog.i}

&SCOPED-DEFINE TimeStamp1 substring(string(year(today), "9999"),3) + string(month(today), "99") + string(day(today), "99")
&SCOPED-DEFINE TimeStamp2 substring(string(time, "HH:MM:SS"), 1, 2) + substring(string(time, "HH:MM:SS"), 4, 2) + substring(string(time, "HH:MM:SS"), 7, 2)

define input parameter vc_inputjson             as character format "x(60)" no-undo.
define input parameter vc_outputjson            as character format "x(60)" no-undo.
define input parameter vc_import                as logical  no-undo.

{proxy/bcinvoicejournalentrydef.i}


define variable v_prefix                     as character        format "x(20)"     no-undo.
define variable v_extn                       as character                           no-undo.
define variable v_infile                     as character        format "X(40)"     no-undo.
define variable v_infile1                    as character        format "X(40)"     no-undo.
define variable v_file1                      as character        format "x(20)"     no-undo.
define variable v_file                       as character        format "x(50)"     no-undo.
define variable dir-file                     as character                           no-undo.
                                             
define variable m_arg1                       as character                           no-undo.
define variable v_tmpstr                     as character                           no-undo.
define variable v_tmpstr1                    as character                           no-undo.
define variable v_flcnt                      as integer                             no-undo.
define variable v_import                        as logical       init   "YES"       no-undo.
define stream   data-stream.                
 
define variable l_fdata                      as character                           no-undo.
define variable m_tmpstr                     as character        format "X(150)"    no-undo.
define variable v_cnt                        as integer    no-undo.
define variable lvi_row_id                   as integer     no-undo.
define variable v_unmtch_inv_ac              like GL.GLCode                         no-undo.
define variable v_dbcode                     as character                           no-undo.
define variable v_layerType1                 as character init "Primary"           no-undo.
define variable v_match_dbcode               as character                           no-undo.
define variable v_LayerType2                 as character init "Primary"           no-undo.
define variable v_dbSetCode                  as character no-undo.

/*For Tax*/
define variable v_taxEnv                     as   character                         no-undo.
define variable v_taxType                    as   character                         no-undo.
define variable v_taxRate                    as   decimal                           no-undo.
define variable v_vatCode                    as   character                         no-undo.
define variable v_taxAccount                 as   character                         no-undo.
define variable v_taxCNAccount               as   character                         no-undo.
define variable v_tzFrom                     as   character                         no-undo.
define variable v_tzTo                       as   character                         no-undo.
define variable v_taxCode                    as   character                         no-undo.
define variable v_taxable                    as   logical                           no-undo.
define variable v_taxExcluded                as  logical                            no-undo.
define variable v_noTax                      as   character        init "NON-TAX"   no-undo.

/* ======== FOR API ========= */
define variable viReturn                     as integer     no-undo.
define variable ilReturnDataset              as logical     no-undo.
define variable ilPartialUpdate              as logical     no-undo.
define variable icPartialUpdateExceptionList as character   no-undo.
define variable ocPrimaryKey                 as character   no-undo.
define variable ocRowid                      as character   no-undo.
define variable oiDraftInstance              as integer     no-undo.
define variable ocPrimaryKeyName             as character   no-undo.
define variable vho                          as handle.
define variable oiReturnStatus               as integer     no-undo.
define buffer b_Currency for Currency.


define variable vi_filecount          as integer                  no-undo.
define variable vi_reccount           as integer                  no-undo.
define variable vc_filename           as character                no-undo.
define variable vc_topath             as character                no-undo.
define variable v_runproagram         as character                 no-undo.
define variable vc_inv_account        as character                no-undo.
define variable vc_traceid            as character                no-undo.
define variable v_errorstatus         as logical                  no-undo.
define variable v_toterrorstatus      as logical initial yes      no-undo.


define temp-table tt_CInvheader no-undo

   field tt_company                             like Company.CompanyCode                      /* Company Code  */
   field tt_CreditorCode                        like Creditor.CreditorCode                    /* supplier code */
   field tt_controlaccount                      like GL.GLCode                                /*Control GL acc*/
   field tt_CInvoiceReference                   like CInvoice.CInvoiceReference               /* reference    */
   field tt_CInvoiceDescription                 like CInvoice.CInvoiceDescription             /* Description */
   field tt_Cinvoicetype                        like Cinvoice.Cinvoicetype                    /* invoice type */
   field tt_Cinvoicepostingdate                 like Cinvoice.Cinvoicepostingdate             /* postiong date */
   field tt_Cinvoicedate                        like Cinvoice.Cinvoicedate                    /* invoice date */       
   field tt_CurrencyCode                        like Currency.CurrencyCode                    /* CURR */
   field tt_ReasonCode                          like Reason.ReasonCode                        /* invoice status code */
   field tt_CInvoiceTSMNumber                   like Cinvoice.CInvoiceTSMNumber               /*Invoice Category*/ 
   field tt_Cinvoiceistaxable                   like Cinvoice.Cinvoiceistaxable               /* tax able */
   field tt_Cinvoiceistaxexcluded               like Cinvoice.Cinvoiceistaxexcluded           /* tax excluded */
   field tt_Cinvoicetaxusage                    as   character                                  /* tax usage */
   field tt_Cinvoicetaxclass                    as   character                                  /* tax class */
   field tt_paymentconditioncode                like paymentcondition.paymentconditioncode    /* Credit terms code */
   field tt_Inv_Divisioncode                    like Division.Divisioncode                    /* sub-account */
   field tt_Inv_costcentrecode                  like costcentre.costcentrecode                /* Cost Center */
   field tt_Inv_projectcode                     like project.projectcode                      /* Project */
   field tt_CinvoiceHoldamountTc                like Cinvoice.CinvoiceHoldamountTc            /* TC Hold Amount */
   field tt_Cinvoiceduedate                     like Cinvoice.Cinvoiceduedate                 /* due date */
   field tt_CInvoiceTaxPointDate                like CInvoice.CInvoiceTaxPointDate            /*Tax Point date SK01*/
   field tt_cinvoiceamount                      as   decimal                                  /* Untax amount */
   field tt_cinvoicetaxamount                    as   decimal                                  /* Tax amount */
   field tt_inputfilename                       as   character                                  /* inputfilename */

   index idx1 tt_CInvoiceReference.


define temp-table tt_CInvLine no-undo
   
   field tt_CInvoiceReference                   like CInvoice.CInvoiceReference               /* reference    */
   field tt_GLCode                              like gl.GLCode                                /* Mathing Posting GL account */
   field tt_Divisioncode                        like Division.Divisioncode                    /* sub-account */
   field tt_costcentrecode                      like costcentre.costcentrecode                /* Cost Center */
   field tt_projectcode                         like project.projectcode                      /* Project */ 
   field tt_safconcept                          as character                                   
   field tt_safcode                             like Saf.safcode                              /* SAF */  
   field tt_PostingLineDebitTC                  like postingline.PostingLineDebitTC           /* PostingLineDebitTC */
   field tt_PostingLineCreditTC                 like postingline.PostingLineCreditTC          /* PostingLineCreditTC */
   field tt_PostingLineText                     like postingline.PostingLineText              /* PostingLineText */
   field tt_TxclTaxCls                          like CinvoiceVAT.TxclTaxCls                   /* Tax Class */
   field tt_TxuTaxUsage                         like Cinvoicevat.TxuTaxUsage                  /* Tax Usage */
   field tt_TxenvTaxEnv                         like Cinvoicevat.TxenvTaxEnv                  /* Tax Environment */
   field tt_TxtyTaxType                         like Cinvoicevat.TxtyTaxType                  /* TAX TYPE */
   field tt_vatcode                             like vat.vatcode                              /* Tax Code */   
   field tt_CInvoiceVatVatBaseDebitTC           like Cinvoicevat.CInvoiceVatVatBaseDebitTC    /* TC base amount(Dr) */
   field tt_CInvoiceVatVatBaseCreditTC          like Cinvoicevat.CInvoiceVatVatBaseCreditTC   /* TC base amount(Cr) */
   field tt_CInvoiceVatVatDebitTC               like Cinvoicevat.CInvoiceVatVatDebitTC        /* TC tax amount(Dr) */
   field tt_CInvoiceVatVatCreditTC              like Cinvoicevat.CInvoiceVatVatCreditTC       /* TC tax amount(Cr) */
 
   
   .

     DEFINE DATASET dsCInv FOR tt_CInvheader , tt_CInvLine
         DATA-RELATION rel1 FOR tt_CInvheader, tt_CInvLine RELATION-FIELDS(tt_CInvoiceReference,tt_CInvoiceReference).

   hdataset = dataset dsCInv:HANDLE.    
                
   
/** Get next rc_RowId fuction **/

function fiGetNextRowID returns character:
    lvi_row_id = lvi_row_id - 1.
    return string(string(lvi_row_id) + "row").
end function. 


/** Validation GCM setting for input output directory **/
  {us/xx/xxworkpath_e.i &outbound=YES &inbound=yes &archive=YES}
   
   m_workpath = m_workpath + "sinv/".
   m_archpath = m_archpath + "sinv/".
   m_outpath = m_outpath + "sinv/".
   m_inpath = m_inpath + "sinv/".


mainloop:
repeat on error undo mainloop, retry mainloop:
   
   
     
      empty temp-table tApiCInvoiceCIJE.
      empty temp-table tApiPostingSafCIJE.   
      empty temp-table tApiCInvoicePostingCIJE.
      empty temp-table tApiPostingCIJE.
      empty temp-table tApiPostingLineCIJE .
      empty temp-table tApiCInvoiceVatCIJE.
      empty temp-table tApiPostingVatCIJE.
      empty temp-table tFcMessages.
      empty temp-table tt_CInvheader.
      empty temp-table tt_CInvLine.
      empty temp-table api_status.
   

   find layer where layertypecode = "OFFICIAL" no-lock no-error.
   assign v_layerType1 = layer.layercode
          v_layerType2 = layer.layercode.
   
   v_runproagram = "".
   vc_traceid = "".

   /* Load data from JSON to temp-table */ 
   vc_outputjson = replace(vc_inputjson,".json",".run.out.json").   
   run loadjsonfile(input vc_inputjson,
                    input vc_outputjson,
                    output vl_RetOK).
   if vl_RetOK then
   do:
    
   /* Pre-validation */   
   empty temp-table api_status.   
   for each tt_CInvheader:
   
   /*Company code*/
   v_tmpstr = "".
   for first Domains no-lock
      where DomainCode = global_domain,
      first Company of Domains no-lock
      where CompanyCode = tt_CInvheader.tt_company:
   end.
   if not available Company then
   {us/bbi/pxmsg.i &msgnum = 28 &msgbuffer = v_tmpstr}
   if v_tmpstr <> "" then
   do:
     v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvheader.tt_company
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
   end.
   output to /home/mfg/inv.log.
   /*Supplier code*/
   v_tmpstr = "".
   vc_inv_account = "".
   for first Creditor no-lock
      where CreditorCode = tt_CInvheader.tt_CreditorCode:
   end.
   if not available Creditor then
   do:
   {us/bbi/pxmsg.i &msgnum = 8601 &msgbuffer = v_tmpstr}
   v_cnt = v_cnt + 1.
   create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvheader.tt_CreditorCode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
   end. /* if not available Creditor then */          
    
    
    else do:
    
    
     for each profile no-lock where profile.profile_id = creditor.InvControlGLProfile_ID    ,
         each   profilelink of profile no-lock,
         each gl where ProfileLink.ProfileLinkObject_ID = GL.GL_ID no-lock.
           vc_inv_account = gl.glcode.
     end.
     
     
     end.
   /*Invoice Reference*/

   /*Invoice type*/
  
 
   /*Posting date*/
   v_tmpstr = "".
   for last Period of company no-lock
      where PeriodStatus     = "PERIODOPEN"
      and PeriodStartDate <= tt_CInvheader.tt_Cinvoicepostingdate
      and PeriodEndDate   >= tt_CInvheader.tt_Cinvoicepostingdate
      and PeriodIsPostingPurchAllow:
   end.
   if available  Period then
   .
   else
   do:
      v_tmpstr1 = "Posting date".
      {us/bbi/pxmsg.i &msgnum = 99457 &msgbuffer = v_tmpstr &msgarg1 = v_tmpstr1}
      if v_tmpstr <> "" then
      do:
      v_cnt = v_cnt + 1.
       create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = string(tt_CInvheader.tt_Cinvoicepostingdate)
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
     end.       
   end.
   
   v_tmpstr = "".
   /*TC amount*/
   if index(string(tt_CInvheader.tt_cinvoiceamount),".") > 0 and
   length(substring(string(tt_CInvheader.tt_cinvoiceamount),index(string(tt_CInvheader.tt_cinvoiceamount),".") + 1)) > 2 then
   do:
      v_tmpstr1 = "TC Amount".
      /*# Amount must round .00*/
      {us/bbi/pxmsg.i &msgnum = 99458 &msgbuffer = v_tmpstr &msgarg1 = v_tmpstr1}
       v_cnt = v_cnt + 1.
      create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = string(tt_CInvheader.tt_cinvoiceamount)
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
   end.
   v_tmpstr = "".
   /* Tax amount*/
   if index(string(tt_CInvheader.tt_cinvoicetaxamount ),".") > 0 and
   length(substring(string(tt_CInvheader.tt_cinvoicetaxamount),index(string(tt_CInvheader.tt_cinvoicetaxamount),".") + 1)) > 2 then
   do:
      v_tmpstr1 = "Tax Amount".
      /*# Amount must round .00*/
      {us/bbi/pxmsg.i &msgnum = 99458 &msgbuffer = v_tmpstr &msgarg1 = v_tmpstr1}
     v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = string(tt_CInvheader.tt_cinvoicetaxamount)
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
   end.
   
   for each tt_CInvLine where tt_CInvLine.tt_CInvoiceReference = tt_CInvheader.tt_CInvoiceReference .
   v_tmpstr = "".
   /*TC Credit amount*/
   if index(string(tt_CInvLine.tt_PostingLineDebitTC),".") > 0 and
   length(substring(string(tt_CInvLine.tt_PostingLineDebitTC),index(string(tt_CInvLine.tt_PostingLineDebitTC),".") + 1)) > 2 then
   do:
      v_tmpstr1 = "TC Credit Amount".
      /*# Amount must round .00*/
      {us/bbi/pxmsg.i &msgnum = 99458 &msgbuffer = v_tmpstr &msgarg1 = v_tmpstr1}
      v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = string(tt_CInvLine.tt_PostingLineDebitTC)
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
   end.
   
   v_tmpstr = "".
   /*TC Debit amount*/
   if index(string(tt_CInvLine.tt_PostingLineCreditTC),".") > 0 and
   length(substring(string(tt_CInvLine.tt_PostingLineCreditTC),index(string(tt_CInvLine.tt_PostingLineCreditTC),".") + 1)) > 2 then
   do:
      v_tmpstr1 = "TC Debit Amount".
      /*# Amount must round .00*/
      {us/bbi/pxmsg.i &msgnum = 99458 &msgbuffer = v_tmpstr &msgarg1 = v_tmpstr1 }
      v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = string(tt_CInvLine.tt_PostingLineCreditTC)
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
   end.
  
   
   
   if not can-find (first ac_mstr no-lock where ac_domain = global_domain
   and ac_code = tt_CInvLine.tt_GLCode) then
   do:
      /* Invalid account code */
      {us/bbi/pxmsg.i &MSGNUM=3052 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
      v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvLine.tt_GLCode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
     
   end. /* if not can-find (first ac_mstr no-  */
   
   if tt_CInvLine.tt_Divisioncode     <> "" then
   do:
      if not can-find (first sb_mstr no-lock where sb_domain = global_domain
      and sb_sub   = tt_CInvLine.tt_Divisioncode   ) then
      do:
         /* Invalid sub account Code */
         {us/bbi/pxmsg.i &MSGNUM=3131 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
         v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvLine.tt_Divisioncode   
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
      end.
   end. /*  if tt_CInvheader.tt_Inv_Divisioncode  <> "" then */
   
   
   if tt_CInvLine.tt_costcentrecode <> "" then
   do:
      if not can-find (first cc_mstr no-lock where cc_domain = global_domain
      and cc_ctr  = tt_CInvLine.tt_costcentrecode ) then
      do:
         /* Invalid cost center */
         {us/bbi/pxmsg.i &MSGNUM=3057 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
         v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvLine.tt_costcentrecode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
        
        
      end.
   end. /*  if tt_CInvLine.tt_costcentrecode <> "" then */
   
 
   
   if tt_CInvLine.tt_projectcode  <> "" then
   do:
      if not can-find (first pj_mstr no-lock where pj_domain = global_domain
      and pj_project   = tt_CInvLine.tt_projectcode ) then
      do:
         /* Invalid Project Code */
         {us/bbi/pxmsg.i &MSGNUM=3128 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
        v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvLine.tt_projectcode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
      end.

      v_tmpstr = "".
      for first gl no-lock
         where glcode = tt_CInvLine.tt_GLCode
         and   GLIsProjectAccount:
         v_tmpstr = "y".
      end.
      if v_tmpstr = "" then
      do:
         /* 99967 # GL Project analaysis is not enabled */
         {us/bbi/pxmsg.i &MSGNUM=99967 &ERRORLEVEL=1 &MSGARG1=tt_CInvLine.tt_GLCode &MSGBUFFER=v_tmpstr }
         
          v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvLine.tt_projectcode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
         
         
      end.
 
   end. /* if tt_CInvheader.tt_Inv_projectcode  <> "" then */
   
   
    if tt_CInvLine.tt_safcode <> "" then
   do:
      for first SAF no-lock
         where safcode = tt_CInvLine.tt_safcode:
      end.
      if not available SAF then
      do:
         {us/bbi/pxmsg.i &MSGNUM=12618 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
         
         
      end.
      
      v_tmpstr = "".
      for each gl no-lock
         where glcode = tt_CInvLine.tt_GLCode
         ,each safstructurelink of gl:
         v_tmpstr = "y".
      end.
      if v_tmpstr = "" then
      do:
         /* 99968 # GL Default SAF Struture is blank */
         {us/bbi/pxmsg.i &MSGNUM=99968 &ERRORLEVEL=1 &MSGARG1=tt_CInvLine.tt_GLCode &MSGBUFFER=v_tmpstr }
        
        
      end.
     
   end. /*  if tt_CInvLine.tt_safcode <> "" then */
   
   end. /*  for each tt_CInvLine where */
   
   /*Currency*/
   if not can-find (first cu_mstr no-lock where
   cu_curr = tt_CInvheader.tt_currencycode) then
   do:
      
      /* Invalid currency code */
      {us/bbi/pxmsg.i &MSGNUM=3088 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
      v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvheader.tt_currencycode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
   end.
   
   /*
   if not can-find (first ac_mstr no-lock where ac_domain = global_domain
   and ac_code = tt_CInvheader.tt_controlaccount) then
   do:
      /* Invalid account code */
      {us/bbi/pxmsg.i &MSGNUM=3052 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
      v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvheader.tt_controlaccount
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
     
     
     
   end.
   */
   if tt_CInvheader.tt_Inv_Divisioncode  <> "" then
   do:
      if not can-find (first sb_mstr no-lock where sb_domain = global_domain
      and sb_sub   = tt_CInvheader.tt_Inv_Divisioncode ) then
      do:
         /* Invalid sub account Code */
         {us/bbi/pxmsg.i &MSGNUM=3131 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
         v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvheader.tt_Inv_Divisioncode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
      end.
   end. /*  if tt_CInvheader.tt_Inv_Divisioncode  <> "" then */
   
   
   if tt_CInvheader.tt_Inv_costcentrecode <> "" then
   do:
      if not can-find (first cc_mstr no-lock where cc_domain = global_domain
      and cc_ctr  = tt_CInvheader.tt_Inv_costcentrecode ) then
      do:
         /* Invalid cost center */
         {us/bbi/pxmsg.i &MSGNUM=3057 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
         v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvheader.tt_Inv_costcentrecode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
        
        
      end.
   end. /*  if tt_CInvheader.tt_Inv_costcentrecode <> "" then */
   
 
   
   if tt_CInvheader.tt_Inv_projectcode  <> "" then
   do:
      if not can-find (first pj_mstr no-lock where pj_domain = global_domain
      and pj_project   = tt_CInvheader.tt_Inv_projectcode ) then
      do:
         /* Invalid Project Code */
         {us/bbi/pxmsg.i &MSGNUM=3128 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
        v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvheader.tt_Inv_projectcode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
      end.

      v_tmpstr = "".
      for first gl no-lock
         where glcode = tt_CInvLine.tt_GLCode
         and   GLIsProjectAccount:
         v_tmpstr = "y".
      end.
      if v_tmpstr = "" then
      do:
         /* 99967 # GL Project analaysis is not enabled */
         {us/bbi/pxmsg.i &MSGNUM=99967 &ERRORLEVEL=1 &MSGARG1=tt_CInvLine.tt_GLCode &MSGBUFFER=v_tmpstr }
         
          v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvheader.tt_Inv_projectcode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
         
         
      end.
 
   end. /* if tt_CInvheader.tt_Inv_projectcode  <> "" then */
   
   if tt_CInvheader.tt_paymentconditioncode <> "" then
   do:
      if not can-find (first PaymentCondition no-lock
      where PaymentConditionCode = tt_CInvheader.tt_paymentconditioncode) then
      do:
         /* Credit terms code does not exist */
         {us/bbi/pxmsg.i &MSGNUM=619 &ERRORLEVEL=1 &MSGBUFFER=v_tmpstr }
         v_cnt = v_cnt + 1.
     create api_status.
     assign api_status.data_seq         = v_cnt
            api_status.traceid          = tt_CInvheader.tt_paymentconditioncode
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Pre-validation"
            api_status.message_string   =  v_tmpstr.
      end.
   end. /*  if tt_CInvheader.tt_paymentconditioncode <> "" then */
   
   
end. /*  for each tt_CInvheader. pre-validation */

end. /*  if vl_RetOK then */

      
if vc_import and vl_RetOK and not can-find(first api_status where api_status.return_status  = "FAILED") then do:  
 
for each tt_CInvheader break by tt_CInvheader.tt_CInvoiceReference.
      
      /* HEADER DETAILS */
      
      for first vd_mstr no-lock where vd_domain = global_domain
                                  and vd_addr    = tt_CInvheader.tt_CreditorCode,
          first dybs_mstr no-lock where dybs_domain = global_domain
                                    and dybs_type   = "2"
                                    and dybs_code   = vd_mstr.vd_daybookset:
          
          assign v_dbSetCode = vd_daybookset.
          if tt_CInvheader.tt_Cinvoicetype = "INVOICE"  then
            v_dbcode    = dybs_invoices_dybk.
          else if tt_CInvheader.tt_Cinvoicetype = "CREDITNOTE"  then
            v_dbcode    = dybs_credit_dybk.
          else if tt_CInvheader.tt_Cinvoicetype = "INVOICECORRECTION"  then
            v_dbcode    = dybs_neg_criv_dybk.
          else if tt_CInvheader.tt_Cinvoicetype = "CREDITNOTECORRECTION"  then
            v_dbcode    = dybs_neg_crcn_dybk.
            
      end. /*  for first vd_mstr */
      /*
      message tt_CInvheader.tt_CreditorCode vd_mstr.vd_daybookset view-as alert-box.
      */
     for first domains where domains.domaincode = global_domain no-lock,
         each domainsharedset of domains no-lock .
     
     find SharedSet of domainsharedset  no-lock no-error.
	  if sharedset.sharedsettypecode = "JOURNAL" then
     do: 

      for first journal where journal.journaltypecode = "MATCHINGENTRYCIREC"
                          and journal.sharedset_id = sharedset.SharedSet_ID     
                          no-lock.
         assign v_match_dbcode = journal.journalcode.
      end.
      
    end.  
    if sharedset.sharedsettypecode = "GL" then
    do:
    find first GL where gl.sharedset_id = sharedset.sharedset_id
                    and gl.glsystemtype = "CIREC"
                    no-lock no-error.
      assign v_unmtch_inv_ac = GL.GLCode .
    end. 
      
      end. /* for first domains where domains.domaincode */
      
      if first-of(tt_CInvheader.tt_CInvoiceReference) then 
      do:
      
      empty temp-table tApiCInvoiceCIJE.
      empty temp-table tApiPostingSafCIJE.   
      empty temp-table tApiCInvoicePostingCIJE.
      empty temp-table tApiPostingCIJE.
      empty temp-table tApiPostingLineCIJE .
      empty temp-table tApiCInvoiceVatCIJE.
      empty temp-table tApiPostingVatCIJE.
      empty temp-table tFcMessages.
      
      
      create tApiCInvoiceCIJE.
      assign
         tApiCInvoiceCIJE.tcCreditorCode                 = tt_CInvheader.tt_CreditorCode
         tApiCInvoiceCIJE.CInvoiceReference              = tt_CInvheader.tt_CInvoiceReference
         tApiCInvoiceCIJE.CInvoiceDescription            = tt_CInvheader.tt_CInvoiceDescription       
         tApiCInvoiceCIJE.tcCurrencyCode                 = tt_CInvheader.tt_CurrencyCode
         tApiCInvoiceCIJE.tcDivisionCode                 = tt_CInvheader.tt_Inv_Divisioncode
         tApiCInvoiceCIJE.tcProjectCode                  = tt_CInvheader.tt_Inv_projectcode
         tApiCInvoiceCIJE.tcCostCentreCode               = tt_CInvheader.tt_Inv_costcentrecode
         tApiCinvoiceCIJE.tcNormalPaymentConditionCode   = tt_CInvheader.tt_paymentconditioncode
         tApiCInvoiceCIJE.CInvoicePostingDate            = tt_CInvheader.tt_Cinvoicepostingdate
         tApiCInvoiceCIJE.CInvoiceDate                   = tt_CInvheader.tt_Cinvoicedate
         tApiCInvoiceCIJE.tcReasonCode                   = tt_CInvheader.tt_ReasonCode
         tApiCInvoiceCIJE.CInvoiceType                   = tt_CInvheader.tt_Cinvoicetype
         tApiCInvoiceCIJE.CInvoiceAllocationStatus       = "NOAllocation"  
         tApiCInvoiceCIJE.tcReasonAllocationStatus       = "Allocation"   
         tApiCInvoiceCIJE.CInvoiceIsTaxable              = tt_CInvheader.tt_Cinvoiceistaxable
         tApiCInvoiceCIJE.CInvoiceIsTaxExcluded          = tt_CInvheader.tt_Cinvoiceistaxexcluded
         tApiCInvoiceCIJE.CInvoiceIsVatDelay             = no      
         tApiCInvoiceCIJE.tcControlGLCode                = if tt_CInvheader.tt_controlaccount <> "" then tt_CInvheader.tt_controlaccount else vc_inv_account
         tApiCInvoiceCIJE.cinvoicecitext                 = tt_CInvheader.tt_CInvoiceDescription 
         tApiCInvoiceCIJE.CInvoiceIsInvoiceApproved      = yes
         tApiCInvoiceCIJE.tc_Rowid                       = fiGetNextRowID()
         tApiCInvoiceCIJE.CInvoiceTaxPointDate           = tt_CInvheader.tt_Cinvoicepostingdate      
         tApiCInvoiceCIJE.CInvoiceTSMNumber              = tt_CInvheader.tt_CInvoiceTSMNumber      .
      if  tt_CInvheader.tt_Cinvoiceistaxexcluded then   
      assign      
         tApiCInvoiceCIJE.tdCInvoiceOriginalTC           = tt_CInvheader.tt_cinvoiceamount - tt_CInvheader.tt_cinvoicetaxamount.
      else
      assign 
         tApiCInvoiceCIJE.tdCInvoiceOriginalTC           = tt_CInvheader.tt_cinvoiceamount + tt_CInvheader.tt_cinvoicetaxamount.
        /*         
         tApiCInvoiceCIJE.CinvoiceHoldamountTc = tt_tc_hold_amt    
         tApiCInvoiceCIJE.CInvoiceDueDate           =  
         tApiCInvoiceCIJE.CInvoiceDayBookSetCode    =     
         tApiCInvoiceCIJE.tcJournalCode             =         
         */
         .
      
      if tt_CInvheader.tt_Cinvoicetype = "INVOICE" or tt_CInvheader.tt_Cinvoicetype = "INVOICECORRECTION" then
         tApiCInvoiceCIJE.CInvoiceOriginalCreditTC  =  tt_CInvheader.tt_cinvoiceamount + tt_CInvheader.tt_cinvoicetaxamount.
      else
         tApiCInvoiceCIJE.CInvoiceOriginalDebitTC   =  tt_CInvheader.tt_cinvoiceamount + tt_CInvheader.tt_cinvoicetaxamount.
      
      /* When invoice currency not equal to base currency */
      if tt_CInvheader.tt_CurrencyCode <> base_curr then
      do:
         for first b_Currency where b_Currency.currencycode = base_curr no-lock:
         end.
         for first Currency where Currency.currencycode = tt_CInvheader.tt_CurrencyCode no-lock:
         end.
         
         for last Exchangeratetype where ExchangeRateTypeCode = "accounting"
            ,last Exchangerate of Exchangeratetype
            where ExchangeRate.FromCurrency_ID =  Currency.Currency_id
            and  ExchangeRate.ToCurrency_ID   =  b_Currency.Currency_id
            and  ExchangeRateValidDateFrom   <=  tt_CInvheader.tt_Cinvoicepostingdate
            and  ExchangeRateValidDateTill   >=  tt_CInvheader.tt_Cinvoicepostingdate:
            assign
               tApiCinvoiceCIJE.CInvoiceExchangeRate = ExchangeRate.ExchangeRate
               tApiCinvoiceCIJE.CInvoiceRateScale    = ExchangeRate.ExchangeRateScale.
         end.
      end.
    
      
      for first Creditor no-lock
         where CreditorCode = tt_CInvheader.tt_CreditorCode,
         first PaymentCondition
         where Paymentcondition_ID = NormalPaymentCondition_ID:
         tApiCInvoiceCIJE.tcNormalPaymentConditionType = PaymentCondition.PaymentConditionPaymentTyp.
      end.
      
      if available vd_mstr then
      find first ad_mstr where ad_domain = global_domain
                           and ad_addr = vd_addr
                           no-lock no-error.
      if available ad_mstr then
         tApiCInvoiceCIJE.tcBusinessRelationCode        =  ad_mstr.ad_bus_relation.
      
      
      /* CInvoice posting Journal entry header  */
      
      create tApiCInvoicePostingCIJE.
      assign
         tApiCInvoicePostingCIJE.tc_Rowid             = fiGetNextRowID()
         tApiCInvoicePostingCIJE.CInvoicePostingType  = "ALLOC"
         tApiCInvoicePostingCIJE.tc_ParentRowid       = tApiCInvoiceCIJE.tc_Rowid 
         .
      
      create tApiCInvoicePostingCIJE.
      assign
         tApiCInvoicePostingCIJE.tc_Rowid             = fiGetNextRowID()
         tApiCInvoicePostingCIJE.CInvoicePostingType  = "INIT"
         tApiCInvoicePostingCIJE.tc_ParentRowid       = tApiCInvoiceCIJE.tc_Rowid 
         .
      
      
      /* CInvoice posting tax Journal entry  */
      
       run getTaxDet(input  vd_mstr.vd_addr,      
                     input  tt_CInvheader.tt_company,
                     input  tt_CInvheader.tt_Cinvoicetaxusage, 
                     input  tt_CInvheader.tt_Cinvoicetaxclass, 
                     input  tt_CInvheader.tt_Cinvoicepostingdate,
                     input  tt_CInvheader.tt_Cinvoiceistaxable,
                     output v_taxEnv,     
                     output v_taxType,
                     output v_taxRate,    
                     output v_vatCode,
                     output v_taxAccount, 
                     output v_tzFrom,
                     output v_tzTo,       
                     output v_taxCode,
                     output v_taxCNAccount).
                     
    
      create tApiCInvoiceVatCIJE.
      
      if tt_CInvheader.tt_Cinvoiceistaxable then
      assign
         tApiCInvoiceVatCIJE.TxclTaxCls                = tt_CInvheader.tt_Cinvoicetaxclass
         tApiCInvoiceVatCIJE.TxuTaxUsage               = tt_CInvheader.tt_Cinvoicetaxusage
         .
      
      assign
         
         tApiCInvoiceVatCIJE.TxenvTaxEnv                =  v_taxEnv
         tApiCInvoiceVatCIJE.TxtyTaxType                =  v_taxType
         tApiCInvoiceVatCIJE.tcVatCode                  =  v_vatCode
         tApiCInvoiceVatCIJE.tcDomainCode               = global_domain
         tApiCInvoiceVatCIJE.tcVatInOut                 = "INPUT"
         tApiCInvoiceVatCIJE.tcNormalTaxGLCode          = v_taxAccount
         tApiCInvoiceVatCIJE.tlIsRecalculateTax         = yes
         tApiCInvoiceVatCIJE.tc_Rowid                   = fiGetNextRowID()
         tApiCInvoiceVatCIJE.tc_ParentRowid             = tApiCInvoiceCIJE.tc_Rowid 
         .
         
      if tt_CInvheader.tt_Cinvoicetype = "INVOICE" or tt_CInvheader.tt_Cinvoicetype = "INVOICECORRECTION" then
      assign
         tApiCInvoiceVatCIJE.CInvoiceVatVatBaseDebitTC  = tt_CInvheader.tt_cinvoiceamount  
         tApiCInvoiceVatCIJE.CInvoiceVatVatDebitTC      = tt_CInvheader.tt_cinvoicetaxamount.    
      else    
      assign   
         tApiCInvoiceVatCIJE.CInvoiceVatVatBaseCreditTC = tt_CInvheader.tt_cinvoiceamount    
         tApiCInvoiceVatCIJE.CInvoiceVatVatCreditTC     = tt_CInvheader.tt_cinvoicetaxamount.                
         
         .
         
    
         /*
      message v_dbcode view-as alert-box.
      */
      /* SI LINE POSTING HEADER */
      create tApiPostingCIJE.
      assign
             tApiPostingCIJE.PostingOriginAddressCode       = tt_CInvheader.tt_CreditorCode
             tApiPostingCIJE.tcJournalCode                  = v_dbcode      
             tApiPostingCIJE.tcLayerTypeCode                = v_layerType1  /* OFFICIAL */
             tApiPostingCIJE.PostingDate                    = tt_CInvheader.tt_Cinvoicepostingdate
             tApiPostingCIJE.PostingText                    = tt_CInvheader.tt_CInvoiceDescription   
             tApiPostingCIJE.tc_Rowid                       = fiGetNextRowID()
             tApiPostingCIJE.PostingBusinessRelationTxt     = ad_mstr.ad_bus_relation.
             
      /* SI LINE POSTING Line */
      create tApiPostingLineCIJE.

       
      if not tt_CInvheader.tt_Cinvoiceistaxexcluded then
      do:
        if tt_CInvheader.tt_Cinvoicetype = "INVOICE" or tt_CInvheader.tt_Cinvoicetype = "INVOICECORRECTION"  then
           assign tApiPostingLineCIJE.PostingLineCreditTC  = tt_CInvheader.tt_cinvoiceamount + tt_CInvheader.tt_cinvoicetaxamount .
         else
           assign tApiPostingLineCIJE.PostingLineDebitTC   = tt_CInvheader.tt_cinvoiceamount + tt_CInvheader.tt_cinvoicetaxamount .
      end.
      else do:
      
       if tt_CInvheader.tt_Cinvoicetype = "INVOICE" or tt_CInvheader.tt_Cinvoicetype = "INVOICECORRECTION"  then
            tApiPostingLineCIJE.PostingLineCreditTC  = tt_CInvheader.tt_cinvoiceamount -  tt_CInvheader.tt_cinvoicetaxamount .
      else
            tApiPostingLineCIJE.PostingLineDebitTC   = tt_CInvheader.tt_cinvoiceamount -  tt_CInvheader.tt_cinvoicetaxamount .
      
      end.
      /*
      message tt_CInvheader.tt_controlaccount fiGetNextRowID() view-as alert-box.
      */
      assign
         tApiPostingLineCIJE.PostingLineSequence = 1
         tApiPostingLineCIJE.tcGLCode            = if tt_CInvheader.tt_controlaccount <> "" then tt_CInvheader.tt_controlaccount else vc_inv_account
         tApiPostingLineCIJE.tcCurrencyCode      = tt_CInvheader.tt_CurrencyCode
         tApiPostingLineCIJE.tcDivisionCode      = tt_CInvheader.tt_Inv_Divisioncode
         tApiPostingLineCIJE.tcCostCentreCode    = tt_CInvheader.tt_Inv_costcentrecode
         tApiPostingLineCIJE.tcProjectCode       = tt_CInvheader.tt_Inv_projectcode
         tApiPostingLineCIJE.tc_Rowid            = fiGetNextRowID()
         tApiPostingLineCIJE.tc_ParentRowid      = tApiPostingCIJE.tc_Rowid 
         .
      /*TAx*/
      if tt_CInvheader.tt_Cinvoiceistaxable then
      do:
         create tApiPostingLineCIJE.
         assign
            tApiPostingLineCIJE.PostingLineSequence = 2.
          if tt_CInvheader.tt_Cinvoicetype = "INVOICE" or tt_CInvheader.tt_Cinvoicetype = "INVOICECORRECTION"  then
           assign
            tApiPostingLineCIJE.PostingLineDebitTC  = tt_CInvheader.tt_cinvoicetaxamount  
            tApiPostingLineCIJE.tcGLCode            = v_taxAccount  .
           else
           assign
            tApiPostingLineCIJE.PostingLineCreditTC = tt_CInvheader.tt_cinvoicetaxamount   
            tApiPostingLineCIJE.tcGLCode            = v_taxCNAccount  .
          assign  
            tApiPostingLineCIJE.tcCurrencyCode      = tt_CInvheader.tt_CurrencyCode
            tApiPostingLineCIJE.tcDivisionCode      = ""
            tApiPostingLineCIJE.tcCostCentreCode    = ""
            tApiPostingLineCIJE.tcProjectCode       = ""
            tApiPostingLineCIJE.tc_Rowid            = fiGetNextRowID()
            tApiPostingLineCIJE.tc_ParentRowid      = tApiPostingCIJE.tc_Rowid .
         
         if available vd_mstr then
         do:
            create tApiPostingVatCIJE.
            assign
               tApiPostingVatCIJE.TxtyTaxType             = v_taxType
               tApiPostingVatCIJE.TxclTaxCls              = tt_CInvheader.tt_Cinvoicetaxclass
               tApiPostingVatCIJE.TxuTaxUsage             = tt_CInvheader.tt_Cinvoicetaxusage
               tApiPostingVatCIJE.TxenvTaxEnv             = v_taxEnv
               tApiPostingVatCIJE.FromTxzTaxZone          = v_tzFrom
               tApiPostingVatCIJE.ToTxzTaxZone            = v_tzTo
               tApiPostingVatCIJE.tcVatCode               = v_taxCode 
               tApiPostingVatCIJE.tcVatCode               = v_taxCode  
               tApiPostingVatCIJE.tcVatInOut              = "input"
               tApiPostingVatCIJE.tc_Rowid                = fiGetNextRowID()
               tApiPostingVatCIJE.tc_ParentRowid          = tApiPostingLineCIJE.tc_Rowid
               tApiPostingVatCIJE.PostingVatTaxTransType  = "22"
               tApiPostingVatCIJE.PostingVatTransType     = "PURCHASE"
               tApiPostingVatCIJE.PostingVatTaxPointDate  = tt_CInvheader.tt_Cinvoicepostingdate 
               .
           if tt_CInvheader.tt_Cinvoicetype = "INVOICE" or tt_CInvheader.tt_Cinvoicetype = "INVOICECORRECTION"  then
           assign
               tApiPostingVatCIJE.PostingVatTaxDebitTC    = tt_CInvheader.tt_cinvoicetaxamount 
               tApiPostingVatCIJE.PostingVatBaseDebitTC   = tt_CInvheader.tt_cinvoiceamount .
           else
           assign
               tApiPostingVatCIJE.PostingVatBaseCreditTC  = tt_CInvheader.tt_cinvoiceamount 
               tApiPostingVatCIJE.PostingVatTaxCreditTC   = tt_CInvheader.tt_cinvoicetaxamount .
         end.
      end.
      

      create tApiPostingLineCIJE.
      if tt_CInvheader.tt_Cinvoiceistaxable then
      assign
         tApiPostingLineCIJE.PostingLineSequence = 3
         tApiPostingLineCIJE.tc_Rowid            = fiGetNextRowID().
      else
      assign
         tApiPostingLineCIJE.PostingLineSequence = 2
         tApiPostingLineCIJE.tc_Rowid            = fiGetNextRowID().
      
      assign
         tApiPostingLineCIJE.tcGLCode            = v_unmtch_inv_ac /* Unmatches Invoices */
         tApiPostingLineCIJE.tcCurrencyCode      = tt_CInvheader.tt_currencycode
         tApiPostingLineCIJE.tcDivisionCode      = ""
         tApiPostingLineCIJE.tcCostCentreCode    = ""
         tApiPostingLineCIJE.tcProjectCode       = ""
         tApiPostingLineCIJE.tc_ParentRowid      = tApiPostingCIJE.tc_Rowid 
         .
      if tt_CInvheader.tt_Cinvoicetype = "invoice" or tt_CInvheader.tt_Cinvoicetype = "INVOICECORRECTION"  then
      do:
      if tt_CInvheader.tt_Cinvoiceistaxexcluded then 
         assign tApiPostingLineCIJE.PostingLineDebitTC  = tt_CInvheader.tt_cinvoiceamount -  tt_CInvheader.tt_cinvoicetaxamount .
      else
         assign tApiPostingLineCIJE.PostingLineDebitTC  = tt_CInvheader.tt_cinvoiceamount .
      end. /*  if tt_Cinvoicetype = "invoice" or  */
      else 
      do:
       if tt_CInvheader.tt_Cinvoiceistaxexcluded then 
      assign tApiPostingLineCIJE.PostingLineCreditTC  = tt_CInvheader.tt_cinvoiceamount -  tt_CInvheader.tt_cinvoicetaxamount.
      else 
      assign tApiPostingLineCIJE.PostingLineCreditTC  = tt_CInvheader.tt_cinvoiceamount.
      end.
      
      /*
      message v_match_dbcode view-as alert-box.
      */
      /* MP POSTING */
      create tApiPostingCIJE.
      assign
         tApiPostingCIJE.PostingOriginAddressCode  = tt_CInvheader.tt_CreditorCode
         tApiPostingCIJE.tcJournalCode             = v_match_dbcode          /* MATCH   */
         tApiPostingCIJE.tcLayerTypeCode           = v_LayerType2       /* OFFICIAL */
         tApiPostingCIJE.PostingDate               = tt_CInvheader.tt_Cinvoicepostingdate
         tApiPostingCIJE.PostingText               = tt_CInvoiceDescription 
         tApiPostingCIJE.tc_Rowid                  = fiGetNextRowID()
         .
      
      create tApiPostingLineCIJE.
    
      assign
         tApiPostingLineCIJE.PostingLineSequence = 1
         tApiPostingLineCIJE.tcGLCode            = v_unmtch_inv_ac /* Unmatches Invoices */
         tApiPostingLineCIJE.tcCurrencyCode      = tt_CInvheader.tt_currencycode
         tApiPostingLineCIJE.tcDivisionCode      = ""
         tApiPostingLineCIJE.tcCostCentreCode    = ""
         tApiPostingLineCIJE.tcProjectCode       = ""
         tApiPostingLineCIJE.tc_Rowid              = fiGetNextRowID()
         tApiPostingLineCIJE.tc_ParentRowid      = tApiPostingCIJE.tc_Rowid 
         .
      if tt_CInvheader.tt_Cinvoicetype = "invoice" or tt_CInvheader.tt_Cinvoicetype = "INVOICECORRECTION"  then
      do:
      if tt_CInvheader.tt_Cinvoiceistaxexcluded then 
         assign tApiPostingLineCIJE.PostingLineCreditTC  = tt_CInvheader.tt_cinvoiceamount -  tt_CInvheader.tt_cinvoicetaxamount .
      else
         assign tApiPostingLineCIJE.PostingLineCreditTC  = tt_CInvheader.tt_cinvoiceamount .
      end. /*  if tt_Cinvoicetype = "invoice" or  */
      else 
      do:
       if tt_CInvheader.tt_Cinvoiceistaxexcluded then 
      assign tApiPostingLineCIJE.PostingLineDebitTC  = tt_CInvheader.tt_cinvoiceamount -  tt_CInvheader.tt_cinvoicetaxamount.
      else 
      assign tApiPostingLineCIJE.PostingLineDebitTC  = tt_CInvheader.tt_cinvoiceamount.
      end.
    v_cnt = 1.
    for each tt_CInvLine where tt_CInvLine.tt_CInvoiceReference = tt_CInvheader.tt_CInvoiceReference  .
     v_cnt = v_cnt + 1.
      create tApiPostingLineCIJE.
      assign
         tApiPostingLineCIJE.PostingLineSequence   = v_cnt
         tApiPostingLineCIJE.PostingLineDebitTC    = tt_CInvLine.tt_PostingLineDebitTC
         tApiPostingLineCIJE.PostingLineCreditTC   = tt_CInvLine.tt_PostingLineCreditTC 
         tApiPostingLineCIJE.PostingLineText       = tt_CInvLine.tt_PostingLineText           
         tApiPostingLineCIJE.tcGLCode              = tt_CInvLine.tt_GLCode
         tApiPostingLineCIJE.tcCurrencyCode        = tt_CInvheader.tt_currencycode 
         tApiPostingLineCIJE.tcDivisionCode        = tt_CInvLine.tt_Divisioncode
         tApiPostingLineCIJE.tcCostCentreCode      = tt_CInvLine.tt_costcentrecode
         tApiPostingLineCIJE.tcProjectCode         = tt_CInvLine.tt_projectcode
         tApiPostingLineCIJE.tc_Rowid              = fiGetNextRowID()
         tApiPostingLineCIJE.tc_ParentRowid        = tApiPostingCIJE.tc_Rowid  
          .         
          

      for first domains where domains.domaincode = global_domain no-lock,
         each domainsharedset of domains no-lock,
       each   SharedSet of domainsharedset where sharedset.sharedsettypecode = "GL" 
       no-lock.

      find first GL where gl.sharedset_id = sharedset.sharedset_id
                    and gl.gltype  = "VAT"
                    and gl.glcode  = tt_CInvLine.tt_GLCode
                    no-lock no-error.
     
      end. /* for first domains where domains.domaincode */
          
       if available gl then
       do:
       
          run getTaxDet(input  vd_mstr.vd_addr,      
                     input  tt_CInvheader.tt_company,
                     input  tt_CInvLine.tt_TxuTaxUsage, 
                     input  tt_CInvLine.tt_TxclTaxCls, 
                     input  tt_CInvheader.tt_Cinvoicepostingdate,
                     input  yes,
                     output v_taxEnv,     
                     output v_taxType,
                     output v_taxRate,    
                     output v_vatCode,
                     output v_taxAccount, 
                     output v_tzFrom,
                     output v_tzTo,       
                     output v_taxCode,
                     output v_taxCNAccount). 
                     
         create tApiPostingVatCIJE.
            assign
               tApiPostingVatCIJE.TxtyTaxType             = tt_TxtyTaxType
               tApiPostingVatCIJE.TxclTaxCls              = tt_CInvLine.tt_TxclTaxCls
               tApiPostingVatCIJE.TxuTaxUsage             = tt_CInvLine.tt_TxuTaxUsage
               tApiPostingVatCIJE.TxenvTaxEnv             = v_taxEnv
               tApiPostingVatCIJE.FromTxzTaxZone          = v_tzFrom
               tApiPostingVatCIJE.ToTxzTaxZone            = v_tzTo
               tApiPostingVatCIJE.tcVatCode               = v_vatCode 
               tApiPostingVatCIJE.tcVatInOut              = "input"
               tApiPostingVatCIJE.tc_Rowid                = fiGetNextRowID()
               tApiPostingVatCIJE.tc_ParentRowid          = tApiPostingLineCIJE.tc_Rowid
               tApiPostingVatCIJE.PostingVatTaxTransType  = "22"
               tApiPostingVatCIJE.PostingVatTransType     = "PURCHASE"
               tApiPostingVatCIJE.PostingVatTaxPointDate  = tt_CInvheader.tt_Cinvoicepostingdate 
               tApiPostingVatCIJE.PostingVatTaxDebitTC    = tt_CInvLine.tt_CInvoiceVatVatDebitTC
               tApiPostingVatCIJE.PostingVatBaseDebitTC   = tt_CInvLine.tt_CInvoiceVatVatBaseDebitTC 
               tApiPostingVatCIJE.PostingVatTaxCreditTC    = tt_CInvLine.tt_CInvoiceVatVatCreditTC
               tApiPostingVatCIJE.PostingVatBaseCreditTC   = tt_CInvLine.tt_CInvoiceVatVatBaseCreditTC
               
               .
               


       end. /* */       
          
      
      end. /* if first-of tt_CInvheader */
   
 /*  
   if tt_saf <> "" then
   do:
      v_tmpstr = "".
      for first gl no-lock
         where glcode = tt_gl_acc
         ,each safstructurelink of gl:
         v_tmpstr = "y".
      end.
      
      for first saf no-lock
         where safcode = tt_saf,
         first safconcept of saf,
         first safstructureline of safconcept,
         first safstructure of safstructureline:
         
         create  tApiPostingSafCIJE.
         assign
            tApiPostingSafCIJE.PostingSafInputSequence = 1
            tApiPostingSafCIJE.tcSafCode = tt_saf
            tApiPostingSafCIJE.tc_Rowid = "SAF" + string(v_cnt)
            tApiPostingSafCIJE.tcSafConceptCode = safconceptcode
            tApiPostingSafCIJE.tcSafStructureCode = safstructurecode
            tApiPostingSafCIJE.tc_ParentRowid = string(v_cnt) + "MP1"
            tApiPostingSafCIJE.tcSafConceptCode = string(tt_safconcept)  /*AK01*/
            .
         
         for first CostCentre no-lock
            where CostCentreCode = tt_cc
            and CostCentreIsStructFromGL:
            assign tApiPostingSafCIJE.PostingSafParentType = "COSTCENTRE".
            
         end.
      end.
   end.
  */
   end. /* if first-of tt_CInvLine.tt_CInvoiceReference */
   
   if  last-of(tt_CInvheader.tt_CInvoiceReference)  then 
   do:
      v_cnt = 0.
      importloop:
      do transaction on error undo importloop, leave importloop:
      
        
      run proxy/bcinvoicejournalentry.p persistent set vhProxyComponent.
      
      /* DO THE VALIDATION BEFORE LOADING */
      run ApiMaintainByDatasetWithOutput in vhProxyComponent
      (input  tt_CInvheader.tt_company,
      input  "validate",
      input  true,
      input  true,
      input  icPartialUpdateExceptionList,
      input  dataset BCInvoiceJournalEntry by-reference,
      output ocPrimaryKey,
      output ocRowid,
      output oiDraftInstance,
      output ocPrimaryKeyName,
      output dataset-handle vho,
      output dataset tFcMessages,
      output oiReturnStatus).


      delete procedure vhProxyComponent.
      
      v_cnt = 0.
      
        
   
      for each tFcMessages :
         if tFCMessages.tcFcType = "W" then next.
         if index(tFcMessages.tcFcMessage,"warning") <> 0 or
         index(tFcMessages.tcFcMessage, "The sum of the base and tax amounts") <> 0 then
         next.
        
         if  index(tFcMessages.tcFcMsgNumber, "qadfin-500498") <> 0 then
         next.

        
         v_cnt = v_cnt + 1.
         if v_cnt > 200 then
         leave.

         
         create api_status.
         assign api_status.data_seq         = v_cnt
            api_status.traceid          = ""
            api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
            api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
            api_status.return_status    = "FAILED" 
            api_status.message_type     = "Import Validation"
         
            api_status.message_string   =  if tFcMessages.tcFcFieldName <> "" 
                                          then gettermlabel("SEVERITY",8) + " = " +
                                          string(tFcMessages.tiFcSeverity) + " | " +
                                          tFcMessages.tcFcMessage + " | " +
                                          gettermlabel("FIELD_NAME",10) + " = " +
                                          tFcMessages.tcFcFieldName + " | " +
                                          gettermlabel("FIELD_LABEL",11) + " = " +
                                          tFcMessages.tcFcFieldLabel + " | " +
                                          gettermlabel("FIELD_VALUE",11) + " = " +
                                          tFcMessages.tcFcFieldValue + " | " +
                                          tFcMessages.tcFcMsgNumber + " " + tFCMessages.tcFcType
                                          else 
                                          gettermlabel("SEVERITY",8) + " = " +
                                          string(tFcMessages.tiFcSeverity) + " | " +
                                          tFcMessages.tcFcMessage + " | " +
                                          tFcMessages.tcFcMsgNumber + " " + tFCMessages.tcFcType.
         
         
      end. /* for each tFcMessages : */
      

      
      /* IF NO ERROR THEN LOAD THE DATA */
      if v_cnt = 0 then
      do:
         run proxy/bcinvoicejournalentry.p persistent set vhProxyComponent.
         
         run ApiMaintainByDatasetWithOutput in vhProxyComponent
         (input  tt_CInvheader.tt_company,
         input  "save",
         input  true,
         input  true,
         input  icPartialUpdateExceptionList,
         input  dataset BCInvoiceJournalEntry by-reference,
         output ocPrimaryKey,
         output ocRowid,
         output oiDraftInstance,
         output ocPrimaryKeyName,
         output dataset-handle vho,
         output dataset tFcMessages,
         output oiReturnStatus).
         
             
         
         for first Cinvoice where CInvoice_ID =  int64(ocPrimaryKey):  
           find first journal no-lock where journal.journal_id = cinvoice.journal_id  no-error.

           v_cnt = v_cnt + 1.
           create api_status.
           assign api_status.data_seq         = v_cnt
                  api_status.traceid          = v_infile1
                  api_status.billnbr           = tt_CInvheader.tt_CInvoiceReference 
                  api_status.dataid           = tt_CInvheader.tt_CInvoiceReference
                  api_status.return_status    = "SUCCESS"  
                  api_status.message_type     = "Loading"
                  api_status.message_string   =  string(Cinvoice.CInvoicePostingYear,"9999") + journal.journalcode + string(Cinvoice.CInvoiceVoucher,"999999999").
      
         
         end. /*  for first Cinvoice */
         
         delete procedure  vhProxyComponent.
          

            end. /* do transaction on error */

      end. /* if v_cnt = 0 then */
   
   
       
      end. /*  if v_import then  */
   end. /* for each tt_CInvheader */
   
   /* Move input file to archive directory */
   
end. /*  if vc_import and vl_RetOK then do:   */
   
   
   
       for each tt_CInvheader break by tt_CInvheader.tt_CInvoiceReference .
       if last-of(tt_CInvheader.tt_CInvoiceReference) then 
       do:
       vi_reccount = vi_reccount + 1.
              
       run CreateAPILogMaster(input vc_traceid,
                              input "createsupplierinvoice",
                              input "xxapmatchingapi.p",
                              input "",
                              input "",
                              input vc_inputjson,
                              input tt_CInvheader.tt_CInvoiceReference,
                              input "",
                              input "xxapisinvdata_det",
                              input vi_reccount).  
                              
       end. /* if last-of(tt_CInvoiceReference.tt_CInvoiceReference) then  */
   
       end. /* for each tt_CInvheader break by tt_CInvheader.tt_CInvoiceReference */
   
   
   
   
          /* Handle cimload related files */
         /* Create output json */                   
         run writejsonfile(input hresult,
                  input vc_outputjson,
                  input "FILE",
                  input True,
                  input "UTF-8",
                  output vl_RetOK,
                  output vc_errorstring).
                  
       
       do vi_filecount = 1 to 5:
          /* when success move cim log file to archive directory  */
          /* when failed move cim log file to error directory  */   
          /*  move status json file to out directory for API return */   
          /* when success move previous step .p and json file to archive directory  */
          /* when failed move previous step .p and json file to error directory  */       
          case vi_filecount:
      
          when 1 then
          assign vc_filename = replace(vc_inputjson,".json",".p")
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 2 then
          assign vc_filename = vc_inputjson
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 3 then
          assign vc_filename = replace(vc_inputjson,".json",".dat")
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 4 then
          assign vc_filename = replace(vc_inputjson,".json",".run.log")
                 vc_topath   = m_outpath.
          when 5 then
          assign vc_filename = replace(vc_inputjson,".json",".run.out.json")
                 vc_topath   =  m_outpath.
          end case.
          

          
          run cimfilehandle(input vc_filename,
                            input vc_topath,
                            input no ).                 
                   
          
     
       end.       /* do vi_filecount = 1 to 5: */    

                  for each tApiCInvoiceCIJE.
                     export tApiCInvoiceCIJE.
                  end.
                  for each tApiPostingSafCIJE. 
                      export tApiPostingSafCIJE.                
                  end.                  
                  for each tApiCInvoicePostingCIJE.
                       export tApiCInvoicePostingCIJE.    
                  end.
                  for each tApiPostingCIJE.
                       export tApiPostingCIJE.  
                  end.
                  for each tApiPostingLineCIJE .
                         export tApiPostingLineCIJE.  
                  end.
                  for each tApiCInvoiceVatCIJE.
                          export tApiCInvoiceVatCIJE.  
                  end.
                  for each tApiPostingVatCIJE.
                         export tApiPostingVatCIJE.  
                  end.
                  for each tFcMessages.
                         export tFcMessages.  
                  end.



         
       
       
       leave.
       
end. /* repeat */


/* END OF PROGRAM */



procedure getTaxDet:
   
   define input  parameter v_input1      as character.
   define input  parameter v_input2      as character.
   define input  parameter v_taxUsage    as character.
   define input  parameter v_tax_class   as character.
   define input  parameter v_pointdate   as date.
   define input  parameter v_taxable     as logical.
   define output parameter v_taxEnv      as character.
   define output parameter v_taxType     as character.
   define output parameter v_taxRate     as decimal.
   define output parameter v_vatCode     as character.
   define output parameter v_taxAccount  as character.
   define output parameter m_from        as character.
   define output parameter m_to          as character.
   define output parameter v_taxCode     as character.
   define output parameter v_taxCNaccount     as character.
   
   define variable m_from1        as character.
   
   def buffer bf_ad_mstr for ad_mstr.
   
   assign
      v_taxEnv    = ""
      v_taxType   = ""
      v_taxRate   = 0
      v_vatCode   = ""
      v_taxAccount= ""
      m_from1 = ""
      v_taxCNaccount = ""
      .
  
   for first creditor no-lock
      where creditorcode = v_input1,
      first businessrelation of creditor,
      first address of businessrelation:
      m_from = address.TxzTaxZone.
   end.
   
   for first company no-lock
      where companycode = v_input2 ,
      first companyproperty of company,
      first businessrelation of companyproperty,
      first address of businessrelation:
      m_to = address.TxzTaxZone.
   end.
   

   
   m_from1 = m_from.
   
   if v_tax_class  <> "" then
   do:
      substring(m_from1,17) = v_tax_class.
   end.
   
   
  
   for first txe_mstr no-lock
      where txe_zone_from = m_from1
      and txe_zone_to   = m_to:
   end.
   if available txe_mstr then
   do:
      v_taxEnv = txe_desc.
      
      for first txed_det no-lock
         where txed_tax_env = txe_desc:
      end.
      if available txed_det then
      do:
         for first vd_mstr no-lock
            where vd_domain = global_domain
            and vd_addr   = v_input1:
         end.
         if available vd_mstr and v_taxable then
         do:
            for last tx2_mstr no-lock
               where tx2_domain    = global_domain
               and tx2_tax_type  = txed_tax_type
               and tx2_pt_taxc   = v_tax_class
               and tx2_tax_usage = v_taxUsage
               and ((tx2_effdate <= v_pointdate and tx2_exp_date = ?)
               or (tx2_effdate <= v_pointdate  and tx2_exp_date >= v_pointdate)):
              
            end.
           
            if available tx2_mstr then
            do:
               assign
                  v_taxType     = tx2_tax_type
                  v_taxRate     = tx2_tax_pct
                  v_taxAccount  = tx2_ap_acct
                  v_taxCNaccount = tx2_ap_cn_acct
                  v_taxCode     = tx2_tax_code
                  .
            end.
         end.
         else
         do:
            for last tx2_mstr no-lock
               where tx2_domain    = global_domain
               and tx2_tax_type  = v_noTax
               and tx2_effdate   < today:
            end.
            if available tx2_mstr then
            do:
           
               assign
                  v_taxType     = tx2_tax_type
                  v_taxRate     = tx2_tax_pct
                  v_taxAccount  = tx2_ap_acct
                  v_taxCNaccount = tx2_ap_cn_acct
                  v_taxCode     = tx2_tax_code
                  .
            end.
         end.
      end.
   end.
   
   for first creditor no-lock
      where creditorcode = v_input1,
      first txu_mstr where creditor.txutaxusage = txu_tax_usage,
      first domains  where domaincode = GLOBAL_DOMAIN,      
      first vat where vat.domain_id   = domains.domain_id   
      and vat.txutaxusage = txu_tax_usage:
      v_vatCode = vatcode.
   end.
   if v_vatCode = "" then
   v_vatCode = v_taxCode.
   
end.





